import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Home from '@/components/Home.vue'
import Welcome from '@/components/Welcome.vue'
import Users from '@/components/User/Users.vue'
import Rights from '@/components/power/Rights.vue'
import Roles from '@/components/power/Roles.vue'
import Category from '@/components/goods/category.vue'
import Params from '@/components/goods/params.vue'
import GoodsList from '@/components/goods/list.vue'
import Add from '@/components/goods/add.vue'
import Order from '@/components/order/order.vue'
import Report from "@/components/report/report.vue"

Vue.use(VueRouter)

const routes = [
  // 路由规则
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    // 子路由
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      {path:'/goods/add',component:Add},
      {path:'/orders',component:Order},
      {path:'/reports',component:Report}
    ],
  },
]

const router = new VueRouter({
  routes,
})

// 挂载路由导航守卫
// 如果用户没有登录，但是直接通过URL访问特定页面，需要重新导航到登录页面。
// 为路由对象，添加 beforeEach 导航守卫
router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页，不需要权限 直接放行
  if (to.path === '/login') return next()
  // 从 sessionStorage 中获取到 保存的 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token，强制跳转到登录页
  if (!tokenStr) return next('/login')
  next() // 直接放行
})
export default router
